<?php

namespace App\Modules\Apicrzs\Services\Users;

use App\Exceptions\Exception;
use App\Library\Junda\src\CardService;
use App\Library\Junda\src\EffectiveService;
use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Admin\Entities\Member\WaterCardModel;
use App\Modules\Apicrzs\Entities\UsersModel;
use App\Modules\Apicrzs\Services\BaseServices;
use App\Traits\CryptAES;
use Illuminate\Support\Facades\DB;
use function Symfony\Component\String\u;
use function Symfony\Component\Translation\t;

class UserCardServices extends BaseServices
{
    public function __construct(UserCardModel $model)
    {
        $token =  \request()->header('token');
        $user_info = CryptAES::decryptToken($token,'user_grzq');
        $this->user_id = $user_info['data']['user_id']??"";
        $this->user_info = $user_info['data']??[];
        $this->model = $model;
        $this->WaterCardModel = new WaterCardModel();
    }
    public function getCardList($params){
        $uid = $this->user_id;
        $model = $this->model->with(['apparatus_info','user_info'])
            ->where(['user_id'=>$uid,'is_delete'=>0]);
        $lists = $model->orderBy($this->model->getKeyName(), 'DESC')
            ->paginate($this->getLimit($params['limit'] ?? 10));
        $lists_items =[];
        foreach ($lists->items() as &$item){
            $item_info = $this->createCardInfoByCardNo($item['card_code']);
            $jd_v_card_id = $item['jd_v_card_id'];
            $cardEffectiveInfo =  EffectiveService::LoadEffListByVCardId($jd_v_card_id);
            $TodayCardEffectiveInfo =  EffectiveService::GetTodayEffMoneyByVCardId($jd_v_card_id);
            $item['remaining_value'] = $item_info['total_balance'];
            $TodayCardEffectiveInfo_value = $TodayCardEffectiveInfo['data'];
            $validity_end_date='';
            if ($cardEffectiveInfo['data']){
                $validity_end_date = date("Y-m-d", strtotime($cardEffectiveInfo['data'][0]['EndDate']));
            }
            $lists_items[] = [
                'user_card_id'=>$item['user_card_id'],
                'card_code'=>$item['card_code'],
                'card_id'=>$item['card_id'],
                'phone'=>$item['phone'],
                'is_default'=>$item['is_default'],
                'remaining_value'=>$item_info['total_balance'],
                'apparatus_info'=>$item['apparatus_info'],
                'end_date'=>$item_info['end_date'],
                'validity_remaining_value'=>$TodayCardEffectiveInfo_value,
                'validity_end_date'=>$validity_end_date,
            ];
        }
        return [
            'current_page' => $lists->currentPage(),
            'per_page'     => $lists->perPage(),
            'count_page'   => $lists->lastPage(),
            'total'        => $lists->total(),
            'data'         => $lists_items,
        ];
    }

    public function getEffListByVCardId($VCardId)
    {

       $ret =  EffectiveService::LoadEffListByVCardId($VCardId);
    }
    public function getCardInfo($params)
    {
        $card_no = $params['card_no']??"";
        if (!$card_no){
            $this->error ='卡号不能为空';
            return false;
        }
        $card_info = $this->model->where(['card_code'=>$card_no])->first();
        if ($card_info){
            $jd_card_info =  $this->UpdateCardInfoByCardNo($card_info,$card_no);
            $jd_v_card_id = $jd_card_info['jd_v_card_id'];
           $card =  EffectiveService::LoadEffListByVCardId($jd_v_card_id);
        }
        $card_info = $this->model->where(['card_code'=>$card_no])->first();
        if (!in_array($card_info['status'],[0,1])) {
            $this->error ='此卡状态异常，请联系客服';
            return false;
        }
        $user_info = UsersModel::getInstance()->user_info($this->user_id);
        if (empty($card_no)){
            $this->error = '此卡不存在!';
            return false;
        }
        return $card_info;
    }

    /**
     *  用户 绑定 水卡
     * @param array $params
     * @return false|void
     * @throws Exception
     */
    public function createBinding(array $params)
    {

        $card_no =  $params['card_no']??"";
        $user_id = $this->user_id;

        $user_info = UsersModel::getInstance()->user_info($user_id);
        $mobile = $user_info['mobile'];
        $nickname = $user_info['nickname'];
        if (!$mobile){
            $this->error='请先绑定手机号';
            return false;
        }
        if (!$nickname){
            $this->error='请先绑定手机号';
            return false;
        }

        if (!$card_no){
            $this->error='此卡无效，请联系客服';
            return false;
        }
        $water_card_info = $this->WaterCardModel->where(['card_no'=>$card_no])->first();
        $user_card = $this->model->where(['card_code'=>$card_no])->first();


        if (!$water_card_info){
            $water_card_info = $water_card_junda = $this->createCardInfoByCardNo($card_no,$mobile);
            CardService::UpdateICBalance($card_no,$nickname,$mobile);
            if (!$water_card_junda){
                $this->error=$this->error;
                return false;
            }
        }
        if (!$user_card){
            $this->error='此卡已绑定，请联系客服';
            return false;
        }
        $junda_phone = $water_card_info['phone'];

//        if ($junda_phone != $mobile){
//            $this->error='账户手机号和水卡绑定手机号不一致，请联系客服';
//            return false;
//        }

        if ($water_card_info['is_used'] == 0){
            $this->error='此卡未开卡';
            return false;
        }
        /* if ($water_card_info['cstatus'] != 0){
            $this->error='此卡已绑定';
            return false;
        }*/
        $bangding['user_id'] = $this->user_id;
        $bangding['card_id'] = $water_card_info['card_id'];
        $bangding['card_code'] = $card_no;
        $bangding['remaining_value'] = $water_card_info['total_balance'];
        $bangding['jd_v_card_id'] = $water_card_info['jd_v_card_id'];
        $bangding['is_electric'] = $water_card_info['is_electric'];
        $bangding['start_date'] = time();
        $bangding['end_date'] =strtotime("+10 year");
        $bangding['status'] = 1;
        $bangding['is_used'] = 1;
        DB::beginTransaction();
        try{
            parent::create($bangding); // TODO: Change the autogenerated stub
            $this->error ='绑定成功';
            $this->WaterCardModel->where(['card_no'=>$card_no])->update(['is_used'=>1,'user_id'=>$this->user_id]);
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    /**
     *  修改默认选
     * @param array $params
     * @return true
     * @throws Exception
     */
    public function updateBinding(array $params)
    {
        $this->model->where(['user_id'=>$this->user_id])->update(['is_default'=>0]);
        $this->update(['user_card_id'=>$params['user_card_id'],'is_default'=>1]);
        return true;
    }
    public function deleteBinding(array $params)
    {
        $card_no =  $params['card_no'];
        $card_info = $this->model->where(['card_code'=>$card_no])->first();
        DB::beginTransaction();
        try{
            parent::delete(['user_card_id'=>$card_info['user_card_id']]); // TODO: Change the autogenerated stub
            DB::commit();
            $this->error ='解绑成功';
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    // 添加水卡  绑定水卡
    public function create(array $params)
    {
        DB::beginTransaction();
        try{
            parent::create($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

    public function update(array $params)
    {
        DB::beginTransaction();
        try{
            parent::update($params); // TODO: Change the autogenerated stub
            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    /**
     * 检测 水卡  信息  骏达
     * @param $params
     * @return bool
     * @throws Exception
     */

    public function getICBalance($params)
    {
        $card_no = $params['card_no'];
        $card_info  = CardService::GetICBalance($card_no);

//        $VCardId = $card_info['rows']['Id'];

//        exit(json_encode($VCardId));
        $VCardId ="ed094670-4b94-4046-a8c9-872e007bd362";
        $card_info_LoadEff = EffectiveService::LoadEffListByVCardId($VCardId);

        exit(json_encode([$VCardId,$card_info_LoadEff,$card_info]));

    }
    // 绑卡 骏达 系统
     public function createCardInfoByCardNo($card_no){
        $response_junda_info = CardService::GetICBalance($card_no);
        if (!$response_junda_info['success']){
            $this->error ='没有此卡信息';
            return false;
        }
        $response_junda_rows = $response_junda_info['rows'];

        if (!$response_junda_rows['IsUsed']){
            $this->error ='此卡未开卡，请联系客服';
            return false;
        }
        $start = strpos($response_junda_rows['StartDate'], '(') + 1;
        $end = strpos($response_junda_rows['StartDate'], ')', $start);
        $StartDate = (substr($response_junda_rows['StartDate'], $start, $end - $start))/1000;
        $end_start = strpos($response_junda_rows['EndDate'], '(') + 1;
        $endend = strpos($response_junda_rows['EndDate'], ')', $end_start);
        $EndDate = (substr($response_junda_rows['EndDate'], $end_start, $endend - $end_start))/1000;

        $create_info['card_no'] = $card_no;//IC卡号
        $create_info['user_id'] = $this->user_id;//余额
        $create_info['total_balance'] = $response_junda_rows['Cmoney'];//余额
        $create_info['give_money'] = $response_junda_rows['GiveMoney'];//赠送金额剩余
        $create_info['buy_money'] = $response_junda_rows['BuyMoney'];//购买金额剩余
        $create_info['con_money'] = $response_junda_rows['ConMoney'];//总消费金额
        $create_info['nick_name'] = $response_junda_rows['NickName'];// 账户 - 昵称
        $create_info['account_name'] = $response_junda_rows['AccountName'];// 账户
        $create_info['phone'] = $response_junda_rows['AccountName'];//
        $create_info['status'] = $response_junda_rows['Status']?1:0;//
        $create_info['is_electric'] = $response_junda_rows['IsElectric']?1:0;//
        $create_info['cstatus'] = $response_junda_rows['Cstate'];//1.正常卡 2.挂失卡 3.分组卡4.失效卡5.不存在的卡6.异常卡7.金额超限
        $create_info['start_no'] = $response_junda_rows['StartNo'];// 开卡
        $create_info['end_no'] = $response_junda_rows['EndNo'];//
        $create_info['start_date'] = date('Y-m-d',$StartDate);//
        $create_info['end_date'] = date('Y-m-d',$EndDate);//
        $create_info['give_start_date'] = date('Y-m-d',$StartDate);//
        $create_info['give_end_date'] = date('Y-m-d',$EndDate);//
        $create_info['is_used'] =$response_junda_rows['IsUsed'];//
        $create_info['jd_v_card_id'] =$response_junda_rows['Id'];//
        $create_info['created_time'] =time();//


        $card_detail = $this->WaterCardModel->getWaterCardByNo($card_no);
        if ($card_detail){
            $this->WaterCardModel->where(['card_no'=>$card_no])->update($create_info); // TODO: Change the autogenerated stub
            $detail = $create_info;
            $detail['phone'] =  $create_info['phone'];
        }else {
            $detail = $this->WaterCardModel->create($create_info); // TODO: Change the autogenerated stub
            $detail['phone'] =  $create_info['phone'];
        }

        $user_card_detail = UserCardModel::getInstance()->getUserByCardNo($card_no);
        if ($user_card_detail){
            UserCardModel::getInstance()->updateUserByCardNo($card_no,[
                'remaining_value'=>$create_info['total_balance'],
                'jd_v_card_id'=>$create_info['jd_v_card_id'],
            ]);
        }
        return $detail;
    }


    public function UpdateCardInfoByCardNo($card_info,$card_no)
    {
        $response_junda_info = CardService::GetICBalance($card_no);
        if (!$response_junda_info['success']){
            $this->error ='没有此卡信息';
            return false;
        }
        $response_junda_rows = $response_junda_info['rows'];
        if(strstr($response_junda_rows['StartDate'], '(')) {
            $start = strpos($response_junda_rows['StartDate'], '(') + 1;
            $end = strpos($response_junda_rows['StartDate'], ')', $start);
            $StartDate = (substr($response_junda_rows['StartDate'], $start, $end - $start))/1000;
            $end_start = strpos($response_junda_rows['EndDate'], '(') + 1;
            $endend = strpos($response_junda_rows['EndDate'], ')', $end_start);
            $EndDate = (substr($response_junda_rows['EndDate'], $end_start, $endend - $end_start))/1000;
        }else{
            $StartDate = strtotime($response_junda_rows['StartDate']);
            $EndDate = strtotime($response_junda_rows['EndDate']);
        }


        $create_info['total_balance'] = $response_junda_rows['Cmoney'];//余额
        $create_info['give_money'] = $response_junda_rows['GiveMoney'];//赠送金额剩余
        $create_info['buy_money'] = $response_junda_rows['BuyMoney'];//购买金额剩余
        $create_info['con_money'] = $response_junda_rows['ConMoney'];//总消费金额
        $create_info['nick_name'] = $response_junda_rows['NickName'];// 账户 - 昵称
        $create_info['account_name'] = $response_junda_rows['AccountName'];// 账户
        $create_info['phone'] = $response_junda_rows['AccountName'];//
        $create_info['status'] = $response_junda_rows['Status']?1:0;//
        $create_info['is_electric'] = $response_junda_rows['IsElectric']?1:0;//
        $create_info['cstatus'] = $response_junda_rows['Cstate'];//1.正常卡 2.挂失卡 3.分组卡4.失效卡5.不存在的卡6.异常卡7.金额超限
        $create_info['start_no'] = $response_junda_rows['StartNo'];// 开卡
        $create_info['end_no'] = $response_junda_rows['EndNo'];//
        $create_info['start_date'] = date('Y-m-d',$StartDate);//
        $create_info['end_date'] = date('Y-m-d',$EndDate);//
        $create_info['give_start_date'] = date('Y-m-d',$StartDate);//
        $create_info['give_end_date'] = date('Y-m-d',$EndDate);//
        $create_info['is_used'] =$response_junda_rows['IsUsed'];//
        $create_info['jd_v_card_id'] =$response_junda_rows['Id'];//
        $create_info['created_time'] =time();//

//        $create_info['card_id'] =$card_id;//
        $user_card_id = $card_info['user_card_id'];
        $card_id = $card_info['card_id'];

//        $this->model->where(['user_card_id'=>$user_card_id])->update($create_info); // TODO: Change the autogenerated stub
        $this->WaterCardModel->where(['card_id'=>$card_id])->update($create_info); // TODO: Change the autogenerated stub


        return $create_info;
    }

    public function getCardSelectLists()
    {

        $res = $this->model->where(['user_id'=>$this->user_id])->get()->toArray();

        exit(json_encode($res));

    }

    /**
     *  生成电子卡
     * @param $params
     * @return void
     */
    public function createElectronicCardGenInfo($params)
    {
        $user_id = $this->user_id;
        $user_info = UsersModel::getInstance()->user_info($user_id);
        $mobile = $user_info['mobile'];
        $nickname = $user_info['nickname'];
        if (!$mobile){
            $this->error='请先绑定手机号，再领取电子水卡';
            return ['code'=>101,'msg'=>$this->error];
        }
        if (!$nickname){
            $this->error='请您完善个人信息，再领取电子卡，【我的->编辑资料】';
            return ['code'=>101,'msg'=>$this->error];
        }
        return ['code'=>101,'msg'=>'功能暂未开通'];
        $user_is_electric_info  =$this->model->getUserCardByIsElectric($user_id);
        if ($user_is_electric_info){
            $electric_card_code = $user_is_electric_info['card_code'];
            return ['code'=>101,'msg'=>'您已有一张电子卡，卡号：'.$electric_card_code];
        }

//        $eid = '2400fa41-390f-468c-9c44-b0fb00fa0190';
        $eid = '5b3c5df3-e4e0-4769-9c90-b0fb01147bf9';

        // 生成一张电子卡
        $junda_card_info = CardService::AddCardGenRecord($eid);

        if (!$junda_card_info['success']){
            $this->error ='没有此卡信息';
            return false;
        }
        $junda_card_info = $junda_card_info['rows'];

        $VCardNo = $junda_card_info['VCardNo'];
        // 用户绑定水卡
        $isUserBalance = CardService::UpdateICBalance($VCardNo,$nickname,$mobile);
        if (!$isUserBalance){
            return;
        }
        $this->createCardInfoByCardNo($VCardNo);
        return true;
    }
}
